class_name GameManagerCore extends Node

# 单例模式
static var instance = null

# 游戏状态
enum GameState {
	MAIN_MENU,      # 主菜单
	WORLD,          # 世界地图
	BATTLE,         # 战斗
	DIALOGUE,       # 对话
	CUTSCENE,       # 过场动画
	GAME_OVER       # 游戏结束
}

# 当前游戏状态
var current_state = GameState.MAIN_MENU

# 游戏管理器组件
var player_controller
var monster_database
var ui_manager
var current_scene

# 信号
signal game_state_changed(new_state, old_state)
signal scene_changed(new_scene)

# 初始化函数
func _init():
	if instance == null:
		instance = self
		_initialize_game()
	else:
		print("警告: GameManager已经被实例化")

# 初始化游戏
func _initialize_game():
	print("初始化游戏管理器")
	
	# 创建幻兽数据库
	monster_database = MonsterDatabase.new()
	add_child(monster_database)
	
	# 连接场景切换信号
	connect("scene_changed", Callable(self, "_on_scene_changed"))
	
	# 创建玩家控制器
	player_controller = PlayerController.new()
	player_controller.initialize("冒险者")
	add_child(player_controller)
	
	# 创建UI管理器
	ui_manager = UIManager.new()
	ui_manager.initialize()
	add_child(ui_manager)
	
	# 添加初始幻兽
	var starter_monster = monster_database.create_monster("fire_slime", 5)
	player_controller.add_starter_monster(starter_monster)
	
	print("游戏管理器初始化完成")

# 改变游戏状态
func change_game_state(new_state):
	var old_state = current_state
	current_state = new_state
	
	print("游戏状态从 %s 切换到 %s" % [get_state_name(old_state), get_state_name(new_state)])
	emit_signal("game_state_changed", new_state, old_state)
	
	# 根据新状态执行相应操作
	match new_state:
		GameState.MAIN_MENU:
			_load_main_menu()
		
		GameState.WORLD:
			_load_world_map()
		
		GameState.BATTLE:
			_start_battle()
		
		GameState.DIALOGUE:
			# 对话状态处理
			pass
		
		GameState.CUTSCENE:
			# 过场动画处理
			pass
		
		GameState.GAME_OVER:
			_game_over()
	
	return true

# 加载主菜单
func _load_main_menu():
	# 这里将来会加载主菜单场景
	print("加载主菜单")
	
	# 临时实现: 直接进入世界地图
	

# 加载世界地图
func _load_world_map():
	var world_scene = load("res://scenes/world/world_scene.tscn").instantiate()
	get_tree().get_root().add_child(world_scene)
	current_scene = world_scene
	print("加载世界地图")
	
	# 设置玩家位置
	player_controller.move_to_area("村庄", 0, 0)
	
	# 设置UI状态
	ui_manager.change_state(ui_manager.UIState.WORLD_MAP)

# 开始战斗
func _start_battle(enemy_type = null, enemy_level = 5):
	print("开始战斗")
	
	# 创建敌方幻兽
	var enemy_monster
	if enemy_type:
		enemy_monster = monster_database.create_monster(enemy_type, enemy_level)
	else:
		# 随机生成敌方幻兽
		enemy_monster = monster_database.get_random_monster("普通", null, enemy_level, enemy_level)
	
	if enemy_monster == null:
		print("错误: 无法创建敌方幻兽")
		return false
	
	# 获取玩家幻兽队伍
	var player_team = player_controller.get_monster_team()
	var enemy_team = [enemy_monster]
	
	# 创建战斗场景
	var battle_scene = load("res://scenes/battle/battle_scene.tscn").instantiate()
	get_tree().get_root().add_child(battle_scene)
	current_scene = battle_scene
	
	# 开始战斗
	battle_scene.start_battle(player_team, enemy_team)
	
	# 设置UI状态
	ui_manager.change_state(ui_manager.UIState.BATTLE)
	
	# 连接战斗结束信号
	battle_scene.connect("battle_ended", Callable(self, "_on_battle_ended"))
	
	emit_signal("scene_changed", battle_scene)
	return true

# 战斗结束回调
func _on_battle_ended(result):
	print("战斗结束，结果: %s" % result)
	
	# 返回世界地图
	await get_tree().create_timer(2.0).timeout
	

# 游戏结束
func _game_over():
	print("游戏结束")
	
	# 显示游戏结束界面
	ui_manager.show_notification("游戏结束", 5.0)
	
	# 返回主菜单
	await get_tree().create_timer(5.0).timeout
	change_game_state(GameState.MAIN_MENU)

# 保存游戏
func save_game():
	print("保存游戏")
	
	# 这里将来会实现存档系统
	player_controller.save_game_data()
	
	ui_manager.show_notification("游戏已保存", 2.0)
	return true

# 加载游戏
func load_game():
	print("加载游戏")
	
	# 这里将来会实现读档系统
	player_controller.load_game_data()
	
	ui_manager.show_notification("游戏已加载", 2.0)
	
	return true

# 获取状态名称
func get_state_name(state = null):
	if state == null:
		state = current_state
	
	match state:
		GameState.MAIN_MENU:
			return "主菜单"
		GameState.WORLD:
			return "世界地图"
		GameState.BATTLE:
			return "战斗"
		GameState.DIALOGUE:
			return "对话"
		GameState.CUTSCENE:
			return "过场动画"
		GameState.GAME_OVER:
			return "游戏结束"
		_:
			return "未知"

# 场景切换处理
func _on_scene_changed(new_scene):
	print("正在切换场景到: ", new_scene.get_path())
	# 调试旧场景释放
	if current_scene:
		print("释放旧场景: ", current_scene.get_path())
		current_scene.queue_free()
		print("旧场景已标记释放")
	
	# 调试新场景添加
	# 先释放旧场景再添加新场景
	if current_scene:
		print("开始释放旧场景:", current_scene.get_path())
		current_scene.queue_free()
		await get_tree().process_frame  # 等待一帧确保完全释放

	current_scene = new_scene
	print("添加新场景到场景树")
	add_child(current_scene)
	current_scene.set_owner(self)  # 设置owner确保场景树整洁
	print("新场景父节点: ", current_scene.get_parent())
	
	# 调试当前场景设置
	# 更新当前主场景
	await get_tree().process_frame
	get_tree().current_scene = current_scene
	print("当前主场景路径: ", get_tree().current_scene.get_path())
	
	# 调试场景树结构
	print("场景根节点子节点数量: ", get_tree().get_root().get_child_count())
	for i in range(get_tree().get_root().get_child_count()):
		var child = get_tree().get_root().get_child(i)
		print("根节点子节点[", i, "]: ", child.name if child.has_method("get_name") else "Unnamed Node")
